
const playlist = new Array
var ircTime = new Array

async function play_video(id, defaults) {
    const audio = document.querySelector('#audio');
    const res = await songdetail(id)//获取歌曲详细信息
    changePlayer(res, defaults)
    addList(id, defaults)
    audio.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`//改变audio的src
    audio.addEventListener('canplay', () => {
        audio.play()
    })
    const lyrics = await songlyric(id)//请求歌词数据
    if (!(lyrics.data.sgc)) {
        setLyrics(lyrics)
    } else {
        $('.pllyric')[0].innerHTML = ''
        $('.pllyric')[0].innerHTML += `<div class="lyric-item">电台节目，无歌词</div>`
    }
    audio.ontimeupdate = function () {//监听audio的timeupdate来实时更新播放进度
        $('.now-time')[0].innerHTML = realFormatSecond(audio.currentTime)
        let progress = audio.currentTime / audio.duration
        $('.ant-slider-handle').css('left', `${progress * 100}%`)
        $('.ant-slider-track').css('width', `${progress * 100}%`)
        const currentTime = audio.currentTime
        for (i = 0; i < ircTime.length; i++) {
            if (currentTime < ircTime[i + 1] && currentTime > ircTime[i]) {
                $('.pllyric>div').removeClass('lyactive')
                $('.pllyric>div').eq(i).addClass('lyactive')
                let top = $('.lyactive')[1].offsetTop - $('.lyactive')[1].parentNode.offsetTop;
                $('.pllyric')[0].scrollTop = top - 84
            }

        }
    }
    audio.addEventListener('ended', () => {
        cutSong(1)
    })
}

function setLyrics(lyrics) {
    $('.pllyric')[0].innerHTML = ''
    ircTime = []
    lydata = lyrics.data.lrc.lyric.trim().split('\n')//对歌词数据进行初处理
    lydata.forEach(element => {
        let items = element.split(/\[|\]/);//对歌词数据进行再处理
        if (items[2]) {
            ircTime.push(parseFloat(items[1].substr(0, 2)) * 60 + parseFloat(items[1].substring(3, 7)))
            $('.pllyric')[0].innerHTML += `<div class="lyric-item">${items[2]}</div>`//将歌词更新       
        }
    })
    // audio.addEventListener('timeupdate', (e) => {
    //     const currentTime = audio.currentTime
    //     for (i = 0; i < ircTime.length; i++) {
    //         if (currentTime < ircTime[i + 1] && currentTime > ircTime[i]) {
    //             $('.pllyric>div').removeClass('lyactive')
    //             $('.pllyric>div').eq(i).addClass('lyactive')
    //         }

    //     }
    // })
}

function changePlayer(res, defaults) {
    $('.songinfo>a>img')[0].src = `${defaults ? defaults.pic : res.data.songs[0].al.picUrl}?param=35x35`//改变播放器歌曲图片
    $('.play-detail>a').first()[0].innerHTML = `${res.data.songs[0].name}`//改变歌曲名称
    $('.play-detail>a').last()[0].innerHTML = `${defaults ? defaults.title : res.data.songs[0].ar[0].name}`//改变作者名称
    $('.total-time')[0].innerHTML = `/${toMinutes(res.data.songs[0].dt)}`//改变歌曲总时间
    $('.play').addClass('playing')
    $('.con-left>a')[0].href = `"https://music.163.com/song/media/outer/url?id=${res.data.songs[0].id}.mp3"`//改变歌曲下载链接
    $('.con-left>span').on('click', () => {//设置重播按钮函数
        audio.currentTime = 0;
        audio.addEventListener('canplay', () => {//当歌曲能够播放时开始播放
            audio.play()
            $('.play').addClass('playing')
        })
    })
    $('.song-name')[0].innerHTML = `${defaults ? defaults.name : res.data.songs[0].name}`//改变歌曲详情中的歌曲名称
}


async function addList(id, defaults) {//加入歌单
    const res = await songdetail(id)//获取歌曲详细信息
    $('.lylist').removeClass('lyactive')
    if (!($('.main-list')[0].innerHTML.includes(`${res.data.songs[0].id}`))) {//更新歌单
        $('.main-list')[0].innerHTML += `<div class='lyactive lylist' onclick="play_video(${res.data.songs[0].id},${defaults ? { title: '${defaults.title}', name: '${defaults.name}', pic: '${defaults.pic}' } : undefined})">
        <div class="songname">${defaults ? defaults.title : res.data.songs[0].name}</div>
        <div class="plsinger">${defaults ? defaults.name : res.data.songs[0].ar[0].name}</div>
        <div class="plduration">${toMinutes(res.data.songs[0].dt)}</div>
    </div>`
        $('.playerlist>span')[0].innerHTML = Number($('.playerlist>span')[0].innerHTML) + 1
        $('.plleft>h3')[0].innerHTML = `播放列表(${$('.playerlist>span')[0].innerHTML})`
        playlist.push({ id, defaults })
    } else {
        const songs = document.querySelectorAll('.songname')
        songs.forEach(element => {
            if (element.innerHTML == `${res.data.songs[0].name}`) {
                element.parentNode.classList.add('lyactive')
            }

        });
    }
}

async function songdetail(id) {//获取歌曲详细信息
    const res = await axios({
        url: `/song/detail?ids=${id}`,
        method: 'post',
    })
    return res
}

async function songlyric(id) {//获取歌词
    const res = await axios({
        url: `/lyric?id=${id}`,
        method: 'get'
    })
    return res
}

function realFormatSecond(second) {//将秒数转换为歌曲时间
    var secondType = typeof second

    if (secondType === 'number' || secondType === 'string') {
        second = parseInt(second)
        var mimute = Math.floor(second / 60)
        second = second - mimute * 60

        return ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
    } else {
        return '00:00'
    }
}



function toMinutes(val) {//将毫秒数转换为歌曲时间
    return (new Date(val).getMinutes() >= 10 ? new Date(val).getMinutes() : '0' + new Date(val).getMinutes()) + ':' + (new Date(val).getSeconds() >= 10 ? new Date(val).getSeconds() : '0' + new Date(val).getSeconds())
}


$('.play').on('click', function () {//点击播放歌曲以及切换样式
    const audio = document.querySelector('#audio');
    $('.play').toggleClass('playing')
    if ($('.play').hasClass('playing')) {
        audio.play()
    } else {
        audio.pause()
    }
})

$('.volume').on('click', function () {
    $('.plvoice').toggle('hide')
})

$('.ant-slider').on('mousedown', function (e) {
    const audio = $('#audio')[0]
    $('.ant-slider-handle').css('left', `${e.offsetX / 4.93}%`)
    $('.ant-slider-track').css('width', `${e.offsetX / 4.93}%`)
    audio.currentTime = audio.duration * (e.offsetX / 493)
    audio.play()
    $('.play').addClass('playing')
    let isMove = true
    $(document)[0].onmousemove = function (e) {
        if (isMove) {
            if (e.clientX < 438) {
                $('.ant-slider-handle').css('left', `0%`)
                $('.ant-slider-track').css('width', `0%`)
                audio.currentTime = audio.duration * 0
            } else if (e.clientX > 935) {
                $('.ant-slider-handle').css('left', `100%`)
                $('.ant-slider-track').css('width', `100%`)
                audio.currentTime = audio.duration
            } else {
                $('.ant-slider-handle').css('left', `${(e.clientX - 438) / 5}%`)
                $('.ant-slider-track').css('width', `${(e.clientX - 438) / 5}%`)
                audio.currentTime = audio.duration * ((e.clientX - 438) / 500)
            }
        }
    }
    $(document)[0].onmouseup = function () {
        audio.play()
        $('.play').addClass('playing')
        isMove = false
        document.onmouseup = null
        document.onmousemove = null
    }
})

$('.slider').on('mousedown', function (e) {
    $('.slider-handle').css('bottom', `${93 - e.offsetY / 0.93}%`)
    $('.slider-track').css('height', `${93 - e.offsetY / 0.93}%`)
    const audio = $('#audio')[0]
    audio.volume = ((93 - e.offsetY) / 93)
    // let isMove = true
    // $('.plvoice').on('mousemove', function (e) {
    //     if (isMove) {
    //         if (e.offsetY < 1) {
    //             $('.slider-handle').css('bottom', `100%`)
    //             $('.slider-track').css('height', `100%`)
    //         } else if (e.offsetY > 92) {
    //             $('.slider-handle').css('bottom', `0%`)
    //             $('.slider-track').css('height', `0%`)

    //         } else {
    //             $('.slider-handle').css('bottom', `${(92 - e.offsetY) / 0.91}%`)
    //             $('.slider-track').css('height', `${(92 - e.offsetY) / 0.91}%`)

    //         }
    //     }
    // })
    // $(document).on('mouseup', function () {
    //     isMove = false
    // })
})



$('.player-detail').on('click', function (e) {
    e.stopPropagation();
})

function cutSong(num) {
    const now = Number($('#audio')[0].src.match(/\d{4,}/)[0])
    let song

    playlist.forEach(element => {
        if (element.id == now) {
            if ((playlist.indexOf(element) + num) < 0) {
                song = playlist.length - 1
            } else {
                song = (playlist.indexOf(element) + num) % playlist.length
            }

        }
    });
    play_video(playlist[song].id, playlist[song].defaults)

    // play_video(playlist[(playlist.indexOf(Number($('#audio')[0].src.match(/\d{4,}/)[0])) + num) < 0 ? playlist.length - 1 : (playlist.indexOf(Number($('#audio')[0].src.match(/\d{4,}/)[0])) + num) % playlist.length])
}



